from elasticsearch import Elasticsearch
import random
from args import *
# 连接到 Elasticsearch
es = Elasticsearch(hosts=ELASTIC_ADDRESS, basic_auth=(ELASTIC_USERNAME, ELASTIC_PASSWORD))

# 索引名称和日期字段名称（替换为你的实际值）
index_name = "process_ck"
date_field_name1 = "news_publicdate"
date_field_name2 = "news_publictime"
# 构建查询以匹配一部分文档（此示例中匹配 50% 的文档）
query = {
    "query": {
        "function_score": {
            "query": {"match_all": {}},
            "random_score": {}  # 随机打分以选择一部分文档
        }
    }
}

# 获取匹配的文档总数
search_results = es.search(index=index_name, body=query)
total_docs = search_results["hits"]["total"]["value"]

# 使用 _update_by_query 操作来更新文档
response = es.update_by_query(
    index=index_name,
    body={
        "script": {
            "source": """
                if (ctx._seq_no % params.random_seed == params.random_offset) {
                    ctx._source.news_publicdate.year = params.new_year;
                    ctx._source.news_publictime.year = params.new_year;
                }
            """,
            "params": {
                "random_seed": total_docs,  # 随机数种子
                "random_offset": random.randint(0, total_docs - 1),  # 随机偏移量
                "new_year": 2023
            }
        },
        "query": query["query"]
    }
)

# 打印更新结果
print(f"Updated {response['updated']} documents.")
